/**
 * 景区管理弹窗组件
 * 用于新增/编辑景区信息
 */

'use client'

import React, { useState, useEffect } from 'react'
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Textarea } from "@/components/ui/textarea"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog"
import { Badge } from "@/components/ui/badge"
import { createAttraction, updateAttraction, getPresetModels, getPresetFloors } from '@/lib/api/attraction'
import { toast } from 'sonner'
import { X } from 'lucide-react'

interface AttractionManagementModalProps {
  isOpen: boolean
  onClose: () => void
  editingAttraction?: {
    id: string
    name: string
    description: string
    center: [number, number]
    bounds: {
      north: number
      south: number
      east: number
      west: number
    }
    modelPath: string
    floors: string[]
  }
  onSuccess?: (attractionData: any) => void
}

export const AttractionManagementModal: React.FC<AttractionManagementModalProps> = ({
  isOpen,
  onClose,
  editingAttraction,
  onSuccess
}) => {
  const [formData, setFormData] = useState({
    name: '',
    description: '',
    centerLng: '',
    centerLat: '',
    modelPath: '',
    floors: [] as string[]
  })
  const [newFloor, setNewFloor] = useState('')
  const [isLoading, setIsLoading] = useState(false)

  const presetModels = getPresetModels()
  const presetFloors = getPresetFloors()

  // 初始化表单数据
  useEffect(() => {
    if (editingAttraction) {
      setFormData({
        name: editingAttraction.name || '',
        description: editingAttraction.description || '',
        centerLng: editingAttraction.center[0].toString(),
        centerLat: editingAttraction.center[1].toString(),
        modelPath: editingAttraction.modelPath || '',
        floors: editingAttraction.floors || []
      })
    } else {
      // 重置为空表单
      setFormData({
        name: '',
        description: '',
        centerLng: '',
        centerLat: '',
        modelPath: '',
        floors: []
      })
    }
  }, [editingAttraction, isOpen])

  const handleInputChange = (field: string, value: string) => {
    setFormData(prev => ({
      ...prev,
      [field]: value
    }))
  }

  const addFloor = (floor: string) => {
    if (floor && !formData.floors.includes(floor)) {
      setFormData(prev => ({
        ...prev,
        floors: [...prev.floors, floor]
      }))
    }
  }

  const removeFloor = (floor: string) => {
    setFormData(prev => ({
      ...prev,
      floors: prev.floors.filter(f => f !== floor)
    }))
  }

  const handleAddCustomFloor = () => {
    if (newFloor.trim()) {
      addFloor(newFloor.trim())
      setNewFloor('')
    }
  }

  const handleSubmit = async () => {
    if (!formData.name.trim()) {
      toast.error('请输入景区名称')
      return
    }

    if (!formData.centerLng || !formData.centerLat) {
      toast.error('请输入中心坐标')
      return
    }

    if (!formData.modelPath) {
      toast.error('请选择3D模型')
      return
    }

    const centerLng = parseFloat(formData.centerLng)
    const centerLat = parseFloat(formData.centerLat)

    if (isNaN(centerLng) || isNaN(centerLat)) {
      toast.error('坐标格式不正确')
      return
    }

    setIsLoading(true)

    try {
      const attractionData = {
        name: formData.name,
        description: formData.description,
        center: [centerLng, centerLat] as [number, number],
        bounds: {
          north: centerLat + 0.01,
          south: centerLat - 0.01,
          east: centerLng + 0.01,
          west: centerLng - 0.01
        },
        modelPath: formData.modelPath,
        floors: formData.floors
      }

      let result
      if (editingAttraction) {
        // 编辑模式
        result = await updateAttraction({
          id: editingAttraction.id,
          ...attractionData
        })
      } else {
        // 新增模式
        result = await createAttraction(attractionData)
      }

      if (result.success) {
        toast.success(result.msg)
        onSuccess?.(result.data)
        onClose()
      } else {
        toast.error(result.msg)
      }
    } catch (error) {
      console.error('提交景区信息失败:', error)
      toast.error('提交失败，请重试')
    } finally {
      setIsLoading(false)
    }
  }

  return (
    <Dialog open={isOpen} onOpenChange={onClose}>
      <DialogContent className="sm:max-w-lg max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            🏛️ {editingAttraction ? '编辑景区信息' : '新增景区'}
          </DialogTitle>
        </DialogHeader>

        <div className="space-y-4">
          {/* 基本信息 */}
          <div className="space-y-3">
            <div>
              <Label htmlFor="attractionName">景区名称 *</Label>
              <Input
                id="attractionName"
                value={formData.name}
                onChange={(e) => handleInputChange('name', e.target.value)}
                placeholder="请输入景区名称"
              />
            </div>

            <div>
              <Label htmlFor="description">景区描述</Label>
              <Textarea
                id="description"
                value={formData.description}
                onChange={(e) => handleInputChange('description', e.target.value)}
                placeholder="请输入景区描述信息"
                rows={3}
              />
            </div>
          </div>

          {/* 位置信息 */}
          <div className="space-y-3 border-t pt-3">
            <div className="text-sm font-medium text-gray-700">位置信息</div>
            
            <div className="grid grid-cols-2 gap-3">
              <div>
                <Label htmlFor="centerLng">中心经度 *</Label>
                <Input
                  id="centerLng"
                  value={formData.centerLng}
                  onChange={(e) => handleInputChange('centerLng', e.target.value)}
                  placeholder="120.1551"
                  type="number"
                  step="any"
                />
              </div>
              <div>
                <Label htmlFor="centerLat">中心纬度 *</Label>
                <Input
                  id="centerLat"
                  value={formData.centerLat}
                  onChange={(e) => handleInputChange('centerLat', e.target.value)}
                  placeholder="30.2741"
                  type="number"
                  step="any"
                />
              </div>
            </div>
          </div>

          {/* 3D模型选择 */}
          <div className="space-y-3 border-t pt-3">
            <div className="text-sm font-medium text-gray-700">3D模型选择</div>
            
            <div>
              <Label htmlFor="modelPath">模型路径 *</Label>
              <Select value={formData.modelPath} onValueChange={(value) => handleInputChange('modelPath', value)}>
                <SelectTrigger>
                  <SelectValue placeholder="选择预设模型" />
                </SelectTrigger>
                <SelectContent>
                  {presetModels.map((model) => (
                    <SelectItem key={model.value} value={model.value}>
                      <div>
                        <div className="font-medium">{model.label}</div>
                        <div className="text-xs text-gray-500">{model.description}</div>
                      </div>
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
          </div>

          {/* 楼层配置 */}
          <div className="space-y-3 border-t pt-3">
            <div className="text-sm font-medium text-gray-700">楼层配置</div>
            
            {/* 当前楼层列表 */}
            {formData.floors.length > 0 && (
              <div className="flex flex-wrap gap-2">
                {formData.floors.map((floor) => (
                  <Badge key={floor} variant="secondary" className="px-2 py-1">
                    {floor}
                    <Button
                      variant="ghost"
                      size="sm"
                      className="ml-1 h-4 w-4 p-0"
                      onClick={() => removeFloor(floor)}
                    >
                      <X className="h-3 w-3" />
                    </Button>
                  </Badge>
                ))}
              </div>
            )}

            {/* 快速添加预设楼层 */}
            <div>
              <Label>快速添加楼层</Label>
              <div className="flex flex-wrap gap-2 mt-2">
                {presetFloors.map((floor) => (
                  <Button
                    key={floor}
                    variant="outline"
                    size="sm"
                    onClick={() => addFloor(floor)}
                    disabled={formData.floors.includes(floor)}
                    className="h-7 px-2 text-xs"
                  >
                    {floor}
                  </Button>
                ))}
              </div>
            </div>

            {/* 自定义楼层 */}
            <div className="flex gap-2">
              <div className="flex-1">
                <Label htmlFor="newFloor">自定义楼层</Label>
                <Input
                  id="newFloor"
                  value={newFloor}
                  onChange={(e) => setNewFloor(e.target.value)}
                  placeholder="输入楼层名称，如：L6"
                  onKeyDown={(e) => e.key === 'Enter' && handleAddCustomFloor()}
                />
              </div>
              <div className="flex items-end">
                <Button onClick={handleAddCustomFloor} size="sm">
                  添加
                </Button>
              </div>
            </div>
          </div>
        </div>

        <DialogFooter className="gap-2">
          <Button variant="outline" onClick={onClose} disabled={isLoading}>
            取消
          </Button>
          <Button onClick={handleSubmit} disabled={isLoading}>
            {isLoading ? '保存中...' : (editingAttraction ? '更新' : '创建')}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  )
}